const db = require('../db')
//获取文章分类信息
module.exports.getArticleCate = function (req, res) {
    const sql = 'select * from ev_article_cate where is_dalete=0'
    db.query(sql, (err, result) => {
        if (err) return res.cc(err)
        res.send({
            status: 0,
            message: '获取文章分类成功！',
            data: result

        })
    })
}
//新增文章分类信息
module.exports.addArticleCate = function (req, res) {
    const sql = 'select * from ev_article_cate where name=? or alias=?'
    db.query(sql, [req.body.name, req.body.alias], (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 2) return res.cc('分类名称与别名都被占用了')
        if (result.length === 1 && result[0].name === req.body.name && result[0].alias === req.body.alias) return res.cc('分类名称与别名都被占用了')
        if (result.length === 1 && result[0].name === req.body.name) return res.cc('分类名称被占用了')
        if (result.length === 1 && result[0].alias === req.body.alias) return res.cc('分类别名被占用了')
        //添加分类
        const sql = 'insert into ev_article_cate set ?'
        db.query(sql, req.body, (err, result) => {
            if (err) return res.cc(err)
            if (result.affectedRows === 1) {
                res.cc('添加分类成功', 0)
            }
        })
    })
}

//删除文章的分类
module.exports.deleteCateById = function (req, res) {
    // res.send('删除  ok')
    const sql = 'update ev_article_cate set is_dalete=1 where id=?'
    db.query(sql, req.params.id, (err, result) => {
        if (err) return res.cc(err)
        if (result.affectedRows === 1) {
            res.cc('删除文章成功', 0)
        }
    })
}
//根据id获取文章分类数据
module.exports.getArtCateById = function (req, res) {
    const sql = 'select * from ev_article_cate where id=?'
    db.query(sql, (err, result) => {
        if (err) return res.cc(err)
        if (result.length !== 1) return res.cc('获取文章分类失败！')
        res.send({
            status: 0,
            message: '获取文章分类成功！',
            data: result[0],
        })

    })
}
//id更新文章分类数据
module.exports.updateCateById = function (req, res) {
    const sql = 'select * from ev_article_cate where id!=? and(name=? or alias=?)'
    db.query(sql, [req.body.Id, req.body.name, req.body.alias], (err, result) => {
        if (err) return res.cc(err)
        if (result.length === 2) return res.cc('分类名称与别名都被占用了')
        if (result.length === 1 && result[0].name === req.body.name && result[0].alias === req.body.alias) return res.cc('分类名称与别名都被占用了')
        if (result.length === 1 && result[0].name === req.body.name) return res.cc('分类名称被占用了')
        if (result.length === 1 && result[0].alias === req.body.alias) return res.cc('分类别名被占用了')

        const sql = 'insert into ev_article_cate set ? id=?'
        db.query(sql, [req.body, req.body.Id], (err, result) => {
            if (err) return res.cc(err)
            if (result.affectedRows === 1) return res.cc('更新分类失败！')
            res.cc('更新分类成功！', 0)

        })

    })
}
